/*
 *  Copyright 2011-2012 Redia A/S
 * 
 *  This file is part of Redias Android Utilities.
 *
 *  Redias Android Utilities is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redias Android Utilities is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redias Android Utilities.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.redia.lib.xmlrpc;

import java.util.Map;

import dk.redia.lib.log.Log;
import dk.redia.lib.utils.AppConfiguration;

public class XmlRpcResultDumper {
	
	private static final String logTag = "XmlRpcResultDumper";
	
	public static String toString(Object xmlRpcResult) {
		StringBuilder result = new StringBuilder();
		recursiveDump(xmlRpcResult, result, "");
		return result.toString();
	}
	
	public static void dump(Object xmlRpcResult) {
		Log.d(XmlRpcResultDumper.logTag, "Generating XmlRpc result dump");
		StringBuilder output = new StringBuilder();
		XmlRpcResultDumper.recursiveDump(xmlRpcResult, output, "");
		// This must use System.out to avoid having
		// output truncated. We check loggingEnabled to avoid printing output
		// when in production mode.
		if (!AppConfiguration.getInstance().getProductionMode()) {
			System.out.println(output.toString());
		}
		Log.d(XmlRpcResultDumper.logTag, "Successfully took dump. Aah, relief.");
	}
	
	@SuppressWarnings("unchecked")
	private static void recursiveDump(Object xmlRpcResult, StringBuilder output, String indent) {
		if (xmlRpcResult instanceof Map<?, ?>) {
			output.append(indent + "{\n");
			Map<String, Object> r = (Map<String, Object>)xmlRpcResult;
			for (String key : r.keySet()) {
				output.append(indent + key + ": \n");
				XmlRpcResultDumper.recursiveDump(r.get(key), output, indent + "  ");
			}
			output.append(indent + ",\n");
			output.append(indent + "}\n");
		} else if (xmlRpcResult instanceof Object[]) {
			output.append(indent + "[\n");
			for (Object o : (Object[]) xmlRpcResult) {
				XmlRpcResultDumper.recursiveDump(o, output, indent + "  ");
				output.append(indent + ",\n");
			}
			output.append(indent + "]\n");
		} else {
			output.append(indent + "(" + xmlRpcResult.getClass().getName() + ") '" + xmlRpcResult.toString() + "'\n");
		}
	}
}
